import { observable, computed, action } from 'mobx';
import { Tools, Toast, Bubble } from 'weaver-mobile';
import { getQueryParams } from '../util';

const jQuery = window.jQuery;

export default class LoginStore {
  @observable loading = false;
  @observable queryParams = getQueryParams();
  @observable logining = false;
  @observable language = {};
  @observable languages = [];
  @observable languageIdentify = [];
  @observable languagesVisible = false;
  @observable data = {};
  @observable labels = {};
  @observable remember = 1;
  @observable remembered = {};
  @observable loginForm = {};
  @observable dynamicPasswordTime = 0;
  @observable seriesnum_ = 0;
  @observable validateCode = '/weaver/weaver.file.MakeValidateCode?seriesnum_=0';
  @observable loginType = 'form';
  @observable qrcodeValidTime = 30;
  @observable qrcodeReqTime = 1;
  @observable qrcodeIsInvalid = false;
  @observable inputlogintype=0;

  @computed get style() {
    const { backgroundconfig = {}, logoconfig = {}, formconfig = {}, loginbuttonconfig = {}, textbuttonconfig = {}, copyrightconfig = {}, qrcodeconfig = {} } = this.data;

    const style = [];
    style.push(`.portal-login {background-color:${backgroundconfig.backgroundColor}}`);
    style.push(`.portal-login-logo-text {color:${logoconfig.fontColor};}`);
    style.push(`.portal-login-logo-text {font-size:${logoconfig.fontSize}px;}`);
    style.push(`.portal-login-logo-text {font-family:${logoconfig.fontFamily};}`);
    style.push(`.portal-login-form-label {color:${formconfig.iconColor};}`);
    style.push(`.portal-login-form-control .am-list-item .am-input-control input::-moz-placeholder {color:${formconfig.fontColor};}`);
    style.push(`.portal-login-form-control .am-list-item .am-input-control input::-ms-input-placeholder {color:${formconfig.fontColor};}`);
    style.push(`.portal-login-form-control .am-list-item .am-input-control input::-webkit-input-placeholder {color:${formconfig.fontColor};}`);
    style.push(`.portal-login-form-control .am-list-item .am-input-control input {color:${formconfig.fontHoveColor};}`);
    style.push(`.portal-login-form-control .am-list-item .am-input-control input {font-size:${formconfig.fontSize}px;}`);
    style.push(`.portal-login-form-control .am-list-item .am-input-control input {font-family:${formconfig.fontFamily};}`);
    style.push(`.portal-login-type-text {color:${textbuttonconfig.fontColor};}`);
    style.push(`.portal-login-type-text {font-size:${textbuttonconfig.fontSize}px;}`);
    style.push(`.portal-login-type-text {font-family:${textbuttonconfig.fontFamily};}`);
    style.push(`.portal-login-language-text {color:${textbuttonconfig.fontColor};}`);
    style.push(`.portal-login-language-text {font-size:${textbuttonconfig.fontSize}px;}`);
    style.push(`.portal-login-language-text {font-family:${textbuttonconfig.fontFamily};}`);
    style.push(`.portal-login-other-text {color:${textbuttonconfig.fontColor};}`);
    style.push(`.portal-login-other-text {font-size:${textbuttonconfig.fontSize}px;}`);
    style.push(`.portal-login-other-text {font-family:${textbuttonconfig.fontFamily};}`);
	style.push(`.portal-login-types {color:${textbuttonconfig.fontColor}}`);
    style.push(`.portal-login-dynamic-text {color:${textbuttonconfig.fontColor};}`);
    style.push(`.portal-login-dynamic-text {font-size:${textbuttonconfig.fontSize}px;}`);
    style.push(`.portal-login-dynamic-text {font-family:${textbuttonconfig.fontFamily};}`);
    style.push(`.portal-login-remember-text {color:${textbuttonconfig.fontColor};}`);
    style.push(`.portal-login-remember-text {font-size:${textbuttonconfig.fontSize}px;}`);
    style.push(`.portal-login-remember-text {font-family:${textbuttonconfig.fontFamily};}`);
    style.push(`.portal-login-forgot-text {color:${textbuttonconfig.fontColor};}`);
    style.push(`.portal-login-forgot-text {font-size:${textbuttonconfig.fontSize}px;}`);
    style.push(`.portal-login-forgot-text {font-family:${textbuttonconfig.fontFamily};}`);
    style.push(`.portal-login-server-text {color:${textbuttonconfig.fontColor};}`);
    style.push(`.portal-login-server-text {font-size:${textbuttonconfig.fontSize}px;}`);
    style.push(`.portal-login-server-text {font-family:${textbuttonconfig.fontFamily};}`);
    if (loginbuttonconfig.imgbtn == undefined) {
      style.push(`.portal-login-button .am-button {visibility:visible}`);
      style.push(`.portal-login-button .portal-login-imgbutton .am-button {visibility:hidden;height:0px;}`);
      style.push(`.portal-login-button .am-button {color:${loginbuttonconfig.fontColor};}`);
      style.push(`.portal-login-button .am-button {font-size:${loginbuttonconfig.fontSize}px;}`);
      style.push(`.portal-login-button .am-button {font-family:${loginbuttonconfig.fontFamily};}`);
      style.push(`.portal-login-button .am-button {background-color:${loginbuttonconfig.backgroundColor};}`);
      if (loginbuttonconfig.opacity != undefined) {
        if (loginbuttonconfig.opacity == 0) {
          style.push(`.portal-login-button .am-button {opacity:0};}`);
        } else {
          style.push(`.portal-login-button .am-button {opacity:${loginbuttonconfig.opacity * 0.01};}`);
        }
      } else {
        style.push(`.portal-login-button .am-button {opacity:1};}`);
      }
      style.push(`.portal-login-button .am-button {border-radius:${loginbuttonconfig.border || '0'}px;}`);
    } else {
      if (loginbuttonconfig.imgbtn == false) {
        style.push(`.portal-login-button .am-button {visibility:visible}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {visibility:hidden;height:0px;}`);
        style.push(`.portal-login-button .am-button {color:${loginbuttonconfig.fontColor};}`);
        style.push(`.portal-login-button .am-button {font-size:${loginbuttonconfig.fontSize}px;}`);
        style.push(`.portal-login-button .am-button {font-family:${loginbuttonconfig.fontFamily};}`);
        style.push(`.portal-login-button .am-button {background-color:${loginbuttonconfig.backgroundColor};}`);
        if (loginbuttonconfig.opacity != undefined) {
          if (loginbuttonconfig.opacity == 0) {
            style.push(`.portal-login-button .am-button {opacity:0};}`);
          } else {
            style.push(`.portal-login-button .am-button {opacity:${loginbuttonconfig.opacity * 0.01};}`);
          }
        } else {
          style.push(`.portal-login-button .am-button {opacity:1};}`);
        }
        style.push(`.portal-login-button .am-button {border-radius:${loginbuttonconfig.border || '0'}px;}`);
      } else {
        style.push(`.portal-login-button .am-button {visibility:hidden;height:0px;}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {visibility:visible}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {background-image:url(${loginbuttonconfig.content});}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {background-size:100% 100%;}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {background-repeat:no-repeat;}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button-primary {background-color:rgba(255,255,255,1);}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {color:${loginbuttonconfig.imgfontColor};}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {font-size:${loginbuttonconfig.imgfontSize}px;}`);
        style.push(`.portal-login-button .portal-login-imgbutton .am-button {font-family:${loginbuttonconfig.imgfontFamily};}`);
        if (loginbuttonconfig.imgopacity != undefined) {
          if (loginbuttonconfig.imgopacity == 0) {
            style.push(`.portal-login-button .portal-login-imgbutton .am-button {opacity:0};}`);
          } else {
            style.push(`.portal-login-button .portal-login-imgbutton .am-button {opacity:${loginbuttonconfig.imgopacity * 0.01};}`);
          }
        } else {
          style.push(`.portal-login-button .portal-login-imgbutton .am-button {opacity:1};}`);
        }
        style.push(`.portal-login-button .portal-login-imgbutton>.am-button {height:40px;line-height:40px;border:none;cursor:pointer;}`);
        if (loginbuttonconfig.isShowtext == undefined) {
          style.push(`.portal-login-button .portal-login-imgbutton .am-button .imgbutton-text {visibility:hidden;height:0px;}`);
        } else {
          if (loginbuttonconfig.isShowtext == true) {
            style.push(`.portal-login-button .portal-login-imgbutton .am-button .imgbutton-text {visibility:visible}`);
          } else {
            style.push(`.portal-login-button .portal-login-imgbutton .am-button .imgbutton-text {visibility:hidden;height:0px;}`);
          }
        }
      }
    }
    style.push(`.portal-login-copyright-text {color:${copyrightconfig.fontColor};}`);
    style.push(`.portal-login-copyright-text {font-size:${copyrightconfig.fontSize}px;}`);
    style.push(`.portal-login-copyright-text {font-family:${copyrightconfig.fontFamily};}`);
    style.push(`.portal-login-qrcode-text {color:${qrcodeconfig.fontColor};}`);
    style.push(`.portal-login-qrcode-text {font-size:${qrcodeconfig.fontSize}px;}`);
    style.push(`.portal-login-qrcode-text {font-family:${qrcodeconfig.fontFamily};}`);

    return style.join('');
  }

  @action
  getLanguages() {
    Tools.callApi({ url: '/api/system/language/base/getActiveLanguage', method: 'GET' }).then(result => {
      const { systemDefaultLang = {}, activeLanguageInfo = [], languageIdentify = [] } = result;

      let language = {};
      for (var key in systemDefaultLang) {
        language = { id: key, language: systemDefaultLang[key] };
      }
      this.language = language;
      this.languages = activeLanguageInfo;
      this.languageIdentify = languageIdentify;

      // 获取登录页标签
      const { id: langid } = language;
      this.getLabels(langid);

      // 获取记住用户名和密码
      this.getRemember();
      this.getRemembered(langid);
    });
  }

  @action
  getLabels(langid) {
    Tools.callApi({ url: '/api/portal/mloginpage/getMLoginPageLabels', method: 'GET', params: { language: langid } }).then(result => {
      const { data = {} } = result;
      this.labels = data;
    });
  }
  @action
  setImputLoginType(type){
    this.inputlogintype=type;
  }	
  @action
  onLanguageChange(key) {
    this.getLabels(key);
    this.getLoginForm({ langid: key });

    const languages = this.languages;
    for (let i = 0, len = languages.length; i < len; i++) {
      const item = languages[i];
      if (item.id == key) {
        this.language = item;
        break;
      }
    }

    this.onLanguagesVisibleChange(false);
  }

  @action
  onLanguagesVisibleChange(visible) {
    this.languagesVisible = visible;
  }

  @action
  onRememberChange(remember) {
    this.remember = remember;
  }

  @action
  onRemember(account, password) {
    const remember = this.remember;
    let remembered = {};
    if (remember == 1) {
      remembered = { account, password };
    } else if (remember == 2) {
      remembered = { account };
    } else if (remember == 3) {
      remembered = {};
    }

    if (window.em && window.em.checkJsApi('setItem')) {
      window.em.setItem({ key: 'login-remember', value: JSON.stringify(remember) });
      window.em.setItem({ key: 'login-remembered', value: JSON.stringify(remembered) });
    } else {
      window.localStorage.setItem('login-remember', JSON.stringify(remember));
      window.localStorage.setItem('login-remembered', JSON.stringify(remembered));
    }
  }

  @action
  getDataByUsing() {
    this.loading = true;
    Tools.callApi({ url: '/api/portal/mloginpage/getMLoginPageByUsing', method: 'GET' }).then(result => {
      const { data = {} } = result;
      this.data = data;

      const { qrcodeconfig = {} } = data;
      const { showQrcode, qrcodeValidTime = 30, qrcodeReqTime = 1, defaultQrcode } = qrcodeconfig;
      this.qrcodeValidTime = qrcodeValidTime;
      this.qrcodeReqTime = qrcodeReqTime;
      if (showQrcode && defaultQrcode) {
        this.loginType = 'qrcode';
      }

      this.loading = false;
    });
  }

  @action
  getDataById(id) {
    this.loading = true;
    Tools.callApi({ url: '/api/portal/mloginpage/getMLoginPage', method: 'GET', params: { id } }).then(result => {
      const { data = {} } = result;
      this.data = data;

      const { qrcodeconfig = {} } = data;
      const { showQrcode, qrcodeValidTime = 30, qrcodeReqTime = 1, defaultQrcode } = qrcodeconfig;
      this.qrcodeValidTime = qrcodeValidTime;
      this.qrcodeReqTime = qrcodeReqTime;
      if (showQrcode && defaultQrcode) {
        this.loginType = 'qrcode';
      }

      this.loading = false;
    });
  }

  @action
  onDataChange(data) {
    this.data = data;
  }

  @action
  getLoginForm(params = {}, callback) {
    const { loginid = '', langid = this.language.id,fromDynamic=this.inputlogintype } = params;

    window.doLoginAction &&
      window.doLoginAction('getLoginForm', {
        queryParams: this.queryParams,
        logintype: '1',
        loginid: loginid,
        langid: langid,
		fromDynamic:fromDynamic,
        callback: result => {
          let { loginFormItems = [], loginFormHiddenItems = [], loginSetting = {}, qrCode = {} } = result;

          this.loginForm = {
            loginFormItems,
            loginFormHiddenItems,
            loginSetting,
            qrCode
          };

          if (callback && typeof callback == 'function') {
            callback();
          }
        }
      });
  }

  @action
  onLoginTypeChange(loginType) {
    this.loginType = loginType;
  }

  @action
  onValidateCodeChange() {
    setTimeout(() => (this.validateCode = `/weaver/weaver.file.MakeValidateCode?seriesnum_=${++this.seriesnum_}`), 50);
  }

  @action
  getDynamicPassword() {
    const { id: langid } = this.language;
    const { loginSetting } = this.loginForm;

    window.doLoginAction &&
      window.doLoginAction('getDynamicPassword', {
        queryParams: this.queryParams,
        logintype: '1',
        langid: langid,
        loginSetting: loginSetting,
        success: params => {
          const { validitySec = 60 } = params;
          this.dynamicPasswordTime = validitySec;

          const _interval = setInterval(() => {
            const time = this.dynamicPasswordTime;
            if (time == 1) {
              window.clearInterval(_interval);
            }
            this.dynamicPasswordTime = time - 1;
          }, 1000);
        }
      });
  }

  @action
  onForgot() {
    const { id: langid } = this.language;
    window.doLoginAction && window.doLoginAction('forgetPassword', { langid: langid });
  }

  @action
  onLogin() {
    const queryParams = this.queryParams;
    const { id: langid } = this.language;
    const { loginSetting } = this.loginForm;
	const fromDynamic=this.inputlogintype;
    this.logining = true;
    window.doLoginAction &&
      window.doLoginAction('login', {
        queryParams: queryParams,
        logintype: '1',
        langid: langid,
        loginSetting: loginSetting,
		fromDynamic:fromDynamic,
        languageIdentify: this.languageIdentify,
        isRememberAccount: this.remember == 1 || this.remember == 2,
        isRememberPassword: this.remember == 1,
        success: (username, password) => {
          this.onRemember(username || '', password || '');
          this.logining = false;

          if (window.em && window.em.checkJsApi('pushToMain')) {
            window.em.pushToMain();
          } else {
            if (queryParams && queryParams.gopage) {
              window.open(decodeURIComponent(queryParams.gopage), '_self');
            } else {			
				if(queryParams &&queryParams.typeid&&queryParams.typeid=='pad'){
					window.open('/wui/index.html?themeType=ECustom&templateId=4&from=static#/main', '_self');    
				}else{
					window.open('/spa/em/mobile.html', '_self');				  
				}
            }
          }
        },
        failure: (params = {}) => {
          if (params.reflashValidateCode) {
            this.onValidateCodeChange();
          }
          this.logining = false;
        }
      });
  }

  @action
  onQCLogin() {
    // 二维码已失效
    if (this.qrcodeIsInvalid) return;

    const queryParams = this.queryParams;
    const { id: langid } = this.language;
    const { qrCode = {} } = this.loginForm;
   
    Tools.callApi({
      url: '/api/hrm/login/qrcode/getQCLoginStatus',
      method: 'POST',
      params: { langid, loginkey: qrCode.loginkey, isie: false }
    }).then(result => {
      if (result.status == '1') {
        if (window.em && window.em.checkJsApi('pushToMain')) {
          const languageIdentify = this.languageIdentify;
          let langid4em = 'zh';
          for (let i = 0, len = languageIdentify.length; i < len; i++) {
            if (languageIdentify[i][langid] && languageIdentify[i][langid] != '') {
              langid4em = languageIdentify[i][langid];
            }
          }
          Tools.callApi({
            url: '/api/ec/dev/app/getSSOCode',
            method: 'GET',
            params: {}
          }).then(ssoRes => {
            window.em.ssoLogin({
              ssokey: ssoRes.keycode,
              lang_type: langid4em,
              account: '',
              into: 0,
              success: res => {
                if (res && res.errCode == 0) {
                  window.em.pushToMain();
                } else {
                  Bubble.error(res.errMsg, 5);
                }
              }
            });
          });
        } else {
          if (queryParams && queryParams.gopage) {
            window.open(decodeURIComponent(queryParams.gopage), '_self');
          } else {
			  if(queryParams &&queryParams.typeid&&queryParams.typeid=='pad'){	
				window.open('/wui/index.html?themeType=ECustom&templateId=4&from=static#/main', '_self');    
			  }else{
				window.open('/spa/em/mobile.html', '_self');				  
			  }
          }
        }
      }
    });
  }

  @action
  onQCLoginStart() {
    this.qrcodeIsInvalid = false; // 二维码生效

    const qrcodeValidTime = this.qrcodeValidTime;
    const qrcodeReqTime = this.qrcodeReqTime;

    let qrcodeUsedTime = 1;
    this.qrcodeCdInterval = window.setInterval(() => {
      if (qrcodeUsedTime >= qrcodeValidTime) {
        this.onQCLoginEnd();
      }
      qrcodeUsedTime++;
    }, 1000);

    this.qrcodeLoginInterval = window.setInterval(() => this.onQCLogin(), qrcodeReqTime * 1000);
  }

  @action
  onQCLoginEnd() {
    this.qrcodeIsInvalid = true;  // 二维码失效
    window.clearInterval(this.qrcodeCdInterval);
    window.clearInterval(this.qrcodeLoginInterval);
  }

  @action
  setRemember(remember) {
    if (remember) {
      if (window.em && window.em.checkJsApi('setItem')) {
        window.em.setItem({ key: 'login-remember', value: JSON.stringify(remember) });
      } else {
        window.localStorage.setItem('login-remember', JSON.stringify(remember));
      }
    }
  }

  @action
  getRemember() {
    if (window.em && window.em.checkJsApi('getItem')) {
      window.em.getItem({
        key: 'login-remember',
        success: result => {
          const remember = result.value;
          this.remember = remember ? JSON.parse(remember) : 1;
        },
        fail: () => {
          this.remember = 1;
        }
      });
    } else {
      const remember = window.localStorage.getItem('login-remember');
      this.remember = remember ? JSON.parse(remember) : 1;
    }
  }

  @action
  setRemembered(remembered) {
    if (remembered) {
      if (window.em && window.em.checkJsApi('setItem')) {
        window.em.setItem({ key: 'login-remembered', value: JSON.stringify(remembered) });
      } else {
        window.localStorage.setItem('login-remembered', JSON.stringify(remembered));
      }
    }
  }

  @action
  getRemembered(langid) {
    if (window.em && window.em.checkJsApi('getItem')) {
      window.em.getItem({
        key: 'login-remembered',
        success: result => {
          const remembered = result.value;
          this.remembered = remembered ? JSON.parse(remembered) : {};

          // 获取登录页表单
          const { account: loginid = '' } = this.remembered;
          this.getLoginForm({ loginid, langid });
        },
        fail: () => {
          this.remembered = {};

          // 获取登录页表单
          const { account: loginid = '' } = this.remembered;
          this.getLoginForm({ loginid, langid });
        }
      });
    } else {
      const remembered = window.localStorage.getItem('login-remembered');
      this.remembered = remembered ? JSON.parse(remembered) : {};

      // 获取登录页表单
      const { account: loginid = '' } = this.remembered;
      this.getLoginForm({ loginid, langid });
    }
  }

  @action
  onServerChange() {
    if (window.em && window.em.checkJsApi('switchServer')) {
      window.em.switchServer();
    } else {
      Toast.info(this.labels.label7, 1);
    }
  }
}
